const App = getApp()
Page({
  data: {
    listsShow: false,
    keywords: '',
    historywords: []
  },
  onLoad () {
    let historywords = wx.getStorageSync('historySearch') || []
    this.setData({ historywords })
  },
  clearInput() {
    this.setData({
        keywords: ''
    })
  },
  inputTyping(e) {
    this.setData({
        keywords: e.detail.value
    })
    if (e.detail.value === '') {
      this.setData({listsShow: false})
    } else {
      this.setData({listsShow: true})
    }
    if (!this.data.keywords) return
    this.initData()
    this.search()
  },
  searchTap () {
    if (!this.data.keywords) return
    this.toLocalStorage(this.data.keywords)
    this.initData()
    this.search()
  },
  searchHis (e) {
    this.setData({
      keywords: e.currentTarget.dataset.keywords
    })
    if (this.data.keywords === '') {
      this.setData({listsShow: false})
    } else {
      this.setData({listsShow: true})
    }
    this.toLocalStorage(this.data.keywords)
    this.initData()
    this.search()
  },
  search() {
    let agent = wx.getStorageSync('agent')
    let { merchants, keywords } = this.data
    let { params } = merchants
    params.sellerId = agent.id
    params.shopName = keywords
    App.HttpService.search(params).then(res => {
      let data = res.data.data
      merchants.items = [...merchants.items, ...data.shopList]
      if (data.shopList.length > 0) {
        params.page = params.page + 1
        merchants.total = data.counts
      }            
      this.setData({merchants})
      this.setData({
        merchants,
        agent,
        'prompt.hidden': merchants.items.length
      })
    })
  },
  toLocalStorage (keyword) { // 添加历史记录
    if (!keyword) {
      return
    }
    let { historywords } = this.data
    historywords.forEach((item, index) => {
      if (item === keyword) {
        historywords.splice(index, 1)
      }
    })
    if (historywords.length < 10) {
      historywords.splice(0, 0, keyword)
    } else {
      historywords.unshift(keyword)
      historywords.pop()
    }
    wx.setStorageSync('historySearch', historywords)
  },
  handleDel () { //清空历史记录
    this.setData({ historywords: [] })
    wx.removeStorageSync('historySearch')
  },
  initData() {
    const merchants = {
      items: [],
      total: '',
      params: {
        page : 1,
        pageCount: 10
      }
    }
    this.setData({
      merchants: merchants
    })
  },
  toMerchant (e) {
    let {id, name} = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/merchants/detail/detail?merchantId=${id}&merchantName=${name}`
    })
  },
  onPullDownRefresh() {
    this.initData()
    this.search()
  },
  onReachBottom() {
    let merchants = this.data.merchants
    if (merchants.items.length === merchants.total) {
      return
    }
    this.search()
  }
})